package com.example.baiduaicem.control;

import com.baidu.aip.nlp.AipNlp;
import com.example.baiduaicem.Common;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author:huayuzhuo
 * @email:2798866329@qq.com
 * @desc:前端功能查询需要的网络请求
 * @datatime: 2022/9/19 14:34
 */
@WebServlet("/nlp")
public class EmotionControl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        //获取前端页面传送的参数
        String content = req.getParameter("content");

        //准备数据，向百度ai平台发起调用,传入可选参数调用接口
        HashMap<String, Object> options = new HashMap<String, Object>();
        // 初始化一个AipNlp
        AipNlp client = new AipNlp(Common.APPID, Common.APPKEY, Common.SECRETKEY);
        // aipnlp发起请求
        JSONObject res = client.sentimentClassify(content, options);
        System.out.println(res.toString(2));

        //把结果返回前端页面
        PrintWriter writer = resp.getWriter();
        writer.write(res.toString(2));

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
